package dshop.action.admin;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Record;

import appbase.exception.BizzException;
import appbase.jfinal.ext.ApiBaseController;
import dshop.AppConst;
import dshop.interceptor.ApiAuthInterceptor;
import dshop.interceptor.ApiReadBodyParamInterceptor;
import dshop.model.User;
import dshop.service.RedisService;

@Before({ ApiReadBodyParamInterceptor.class, ApiAuthInterceptor.class })
public class UserAction extends ApiBaseController {

	@Clear
	@Before(ApiReadBodyParamInterceptor.class)
	public void login() {
		String account = getPara("account");
		String password = getPara("password", "").toLowerCase();

		User user = User.findBy(account, User.ROLE_ADMIN);

		if (user == null || !User.checkPass(User.encryptPass(password, user.getStr("salt")), user.getStr("password"))
				|| user.getInt("isDel") == AppConst.DELETE_YES) {
			renderFail("用户名或密码错误");
			return;
		}

		int userId = user.getInt("id");
		int role = user.getInt("role");
		String address = user.getStr("address");
		String userPhone = user.getStr("user");

		Record logInfo = loginSuccessHandle(userId, role, address, userPhone);
		setAttr("user", logInfo);

		/*
		 * List<String> permList = PermissionUser.listOf(userId); setAttr("permList",
		 * permList);
		 */

		UsernamePasswordToken token = new UsernamePasswordToken(account, password);
		token.setRememberMe(false);
		SecurityUtils.getSubject().login(token);

		renderSuccess("登录成功");
	}

	@Clear
	@Before(ApiReadBodyParamInterceptor.class)
	public void logout() {
		int userId = getApiUserId();

		RedisService.clearApiAuth(userId);

		SecurityUtils.getSubject().logout();

		renderSuccess("退出成功");
	}

	public void passModify() {
		int userId = getApiUserId();

		String oldPass = getPara("oldPass");
		String newPass = getPara("newPass");
		String confirmPass = getPara("confirmPass");
		int role = getParaToInt("role");

		try {
			User.modifyPass(userId, role, oldPass, newPass, confirmPass);
		} catch (Exception e) {
			e.printStackTrace();
			renderFail(e.getMessage());
			return;
		}
		renderSuccess("修改成功，新密码已经生效。");
	}

	/**
	 * @return {userId, token}
	 */
	private static Record loginSuccessHandle(int userId, int role, String address, String userPhone) {
		String token = ApiAuthInterceptor.createToken(userId);

		Record loginInfo = new Record();
		loginInfo.set(ApiBaseController.PARAM_API_KEY_USER_ID, userId).set(ApiBaseController.PARAM_API_KEY_TOKEN, token)
				.set("role", role).set("address", address).set("userPhone", userPhone);

		// 缓存 token
		RedisService.cacheApiAuth(token, userId, userPhone);
		return loginInfo;
	}

	public void regist() {
		String account = getPara("account");
		String checkPass = getPara("checkPass");
		String user = getPara("user");
		String address = getPara("address");
		String parent = getPara("parentId");
		int role = getParaToInt("role");

		try {
			User.regist(account, checkPass, role, address, parent, user);
		} catch (BizzException e) {
			renderFail("账号已存在");
			return;
		}

		renderSuccess("注册成功");
	}

	public void listOfUser() {

		String select = "select id,account,password,salt,userId,role,address,user,isDel ";
		String where = "  from user where role != 100";

		List<Object> params = new ArrayList<Object>();
		page(select, where, params.toArray());
		renderSuccess();
	}

	public void setSeal() {
		int accountId = getParaToInt("id");
		int role = getParaToInt("role");

		User.delete(accountId, role);
		renderSuccess("禁用成功");
	}

	public void setNormal() {
		int accountId = getParaToInt("id");
		int role = getParaToInt("role");

		User.recover(accountId, role);
		renderSuccess("恢复成功");
	}

}
